package avicit.bdp.dcs.utils.api.response;

import avicit.bdp.dcs.utils.api.Configuration;
import avicit.bdp.dcs.utils.api.HttpReaderErrorCode;
import avicit.bdp.dcs.utils.api.enums.Key;
import avicit.platform6.core.exception.BusinessException;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;

public abstract class ResponseAdapter {

    private static final Logger LOG = LoggerFactory.getLogger(ResponseAdapter.class);

    /**
     * 解析响应数据
     * @param readerSliceConfig
     * @param recordSender
     * @param result
     * @param columnList
     */
    public abstract String parseResponseData(Configuration readerSliceConfig, ResponseEntity<String> result);

    /**
     * 解析状态码
     * @param result
     */
    public void parseStatusCode(Configuration readerSliceConfig, ResponseEntity<String> result){
        String body = result.getBody();
        LOG.info("body = " + body);

        JSONObject jsonObject = JSONObject.parseObject(body);

        String statusCodeField = readerSliceConfig.getString(Key.STATUS_CODE_FIELD);
        if(StringUtils.isNotEmpty(statusCodeField)){
            readerSliceConfig.getNecessaryValue(Key.SUCCESS_STATUS_CODE, HttpReaderErrorCode.SUCCESS_STATUS_CODE_NOT_FIND_ERROR);
            String statusCode = jsonObject.getString(statusCodeField);

            String successStatusCode = readerSliceConfig.getString(Key.SUCCESS_STATUS_CODE);
            if(successStatusCode != null && !statusCode.equals(successStatusCode)){
                String msg = String.format("API接口返回状态失败,返回状态码:%s", statusCode);
                LOG.error(msg);
                throw new BusinessException(msg);
            }
        }
    }

}
